package com.qiezi.project.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.qiezi.App;
import com.qiezi.R;
import com.qiezi.base.BaseMvpActivity;
import com.qiezi.base.BaseMvpFragment;
import com.qiezi.bean.ResponseBean;
import com.qiezi.bean.VersionBean;
import com.qiezi.project.fragment.CategoryFragment;
import com.qiezi.project.fragment.TabsFragment;
import com.qiezi.project.fragment.MyFragment;
import com.qiezi.project.fragment.RecyListFragment;
import com.qiezi.util.AESUtil;
import com.qiezi.util.Request;
import com.qiezi.util.UpdateAppHttpUtil;
import com.qiezi.util.Util;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;


public class MainActivity extends BaseMvpActivity implements View.OnClickListener {

    public class ImageTabEntity implements CustomTabEntity {
        private int selectdIcon;
        private String title;
        private int unSelectdIcon;

        public ImageTabEntity(String paramString, int paramInt1, int paramInt2) {
            this.title = paramString;
            this.selectdIcon = paramInt1;
            this.unSelectdIcon = paramInt2;
        }

        public int getTabSelectedIcon() {
            return this.selectdIcon;
        }

        public String getTabTitle() {
            return this.title;
        }

        public int getTabUnselectedIcon() {
            return this.unSelectdIcon;
        }
    }


    @BindView(R.id.bottomBar)
    CommonTabLayout bottomBar;

    private int[] mIconUnselectIds = {R.drawable.ic_home_us,R.drawable.ic_recommend_us,R.drawable.ic_category_us,R.drawable.ic_site_us,R.drawable.ic_my_us};
    private int[] mIconSelectIds = {R.drawable.ic_home_s,R.drawable.ic_recommend_s,R.drawable.ic_category_s,R.drawable.ic_site_s,R.drawable.ic_my_s};
    private String[] titles = {"首页","推荐","分类","站点","我的"};
    private BaseMvpFragment[] fragmentArr = {
            new TabsFragment().setType(TabsFragment.TabsType.home),
            new TabsFragment().setType(TabsFragment.TabsType.recommend),
            new CategoryFragment(),
            new RecyListFragment().setType(RecyListFragment.HomePageType.site),
            new MyFragment()
    };

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }



    @Override
    protected void initData(Bundle saveBundle) {
        ArrayList<CustomTabEntity> entities = new ArrayList<>(5);
        ArrayList<Fragment> fragments = new ArrayList<>(5);
        for (int i = 0;i<titles.length;i++){
            entities.add(new ImageTabEntity(titles[i],mIconSelectIds[i],mIconUnselectIds[i]));
            fragments.add(fragmentArr[i]);
        }
        bottomBar.setTabData(entities,this,R.id.fragmentContent,fragments);
        bottomBar.setIconGravity(Gravity.CENTER);


        upDate();

    }


    public void upDate(){
        Map<String,String> params = new HashMap<>();
        String timestamp = Request.getSecondTimestamp(new Date());
        String sign = AESUtil.md5(timestamp+Request.SIGNATURE);
        params.put("token", App.getInstance().getToken());
        params.put("time",timestamp);
        params.put("sign",sign);
        params.put("version_code",Util.getVersionCode(this).toString());
        new UpdateAppManager.Builder().setActivity(this)
                .setPost(true)
                .setHttpManager(new UpdateAppHttpUtil())
                .setUpdateUrl(Request.Api.checkVersion.getApi())
                .setParams(params)
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        ResponseBean<VersionBean> data = JSON.parseObject(json,new TypeReference<ResponseBean<VersionBean>>(){});
                        if (data.isSuccess()){
                            VersionBean v = data.getData();
                            updateAppBean
                                    .setUpdate(v.hasUpdate())//（必须）是否更新Yes,No
                                    .setNewVersion(v.getVersion_name())//（必须）新版本号
                                    .setApkFileUrl(v.getDownload_url())//（必须）下载地址
                                    .setUpdateLog(v.getModify_content())//（必须）更新内容
                                    .setTargetSize(v.getApk_size().toString())//大小，不设置不显示大小，可以不设置
                                    .setConstraint(v.isForce())//是否强制更新，可以不设置
                                    .setNewMd5(v.getApk_md5());//设置md5，可以不设置
                        }else {
                            updateAppBean.setUpdate("No");
                        }

                        return updateAppBean;
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {

//                        CProgressDialogUtils.showProgressDialog(JavaActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
//                        CProgressDialogUtils.cancelProgressDialog(JavaActivity.this);
                    }

                });
    }


    @Override
    protected void initListener() {

    }


    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        if (paramBundle != null){
            int index = paramBundle.getInt("index");
            bottomBar.setCurrentTab(index);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle paramBundle) {
        super.onSaveInstanceState(paramBundle);
        paramBundle.putInt("index",bottomBar.getCurrentTab());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
        }
    }



    private void showHome(){
        bottomBar.setCurrentTab(0);
        ((TabsFragment)fragmentArr[0]).showFirstPage();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        log("resultCode:"+resultCode);
        if (resultCode == RESULT_OK){
            log("requestCode:"+requestCode);
            switch (requestCode){
                case WatchHistoryActivity.REQUEST_CODE:
                    showHome();
                    break;
                case CollectionActivity.REQUEST_CODE:
                    showHome();
                    break;
                case DownloadActivity.REQUEST_CODE:
                    showHome();
                    break;
            }
        }
    }
}
